package com.shanghaionstar.activity;

import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by Rengui Lu on 2017/5/9.
 */
public class OkHttpFileUploader {

    private OkHttpClient mOkHttpClient;//okHttpClient 实例
    /**
     * 初始化RequestManager
     */
    public OkHttpFileUploader() {
        //初始化OkHttpClient
        mOkHttpClient = new OkHttpClient();
        mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);//设置超时时间
        mOkHttpClient.setReadTimeout(15, TimeUnit.SECONDS);//设置读取超时时间
        mOkHttpClient.setWriteTimeout(30, TimeUnit.SECONDS);//设置写入超时时间
    }

    /**
     * @param uploadUrl put请求地址
     * @param localPath 本地文件路径
     * @return 响应的结果 和 HTTP status code
     * @throws IOException
     */
    public Response uploadImgFile(String uploadUrl, String localPath,String extension) throws IOException {
        File file = new File(localPath);
        RequestBody body = RequestBody.create(null, file);
        MultipartBuilder builder = new MultipartBuilder();
        builder.addFormDataPart("extension",extension);
        builder.addFormDataPart("imageFile",file.getName(),body);
        body =builder.build();
        Request request = new Request.Builder()
                .url(uploadUrl)
                .post(body)
                .build();
        Response response = mOkHttpClient.newCall(request).execute();
        return  response;
    }

}
